import CryptoUtils from '@/utils/crypto-utils';
import ProtocolUtils from '@/utils/protocol-utils';

const BLUFI_SERVICE = '0000FFFF-0000-1000-8000-00805F9B34FB';
const WRITE_CHAR = '0000FF01-0000-1000-8000-00805F9B34FB';
const NOTIFY_CHAR = '0000FF02-0000-1000-8000-00805F9B34FB';



export default class BluFiController {
	constructor() {
		this.deviceId = null;
		this.deviceMac = '';
		this.keyHex = '';
		this.isConnected = false;
	}

	// 初始化蓝牙
	async init() {
		await this._checkBluetooth();
		const device = await this._scanDevice();
		await this._connectDevice(device);
		await this._setupServices();
	}

	// 发送 WiFi 凭证
	async sendCredentials(ssid, password) {
		// const ssidData = new TextEncoder().encode(ssid);
		const ssidPackets = ProtocolUtils.splitPackets(
			ProtocolUtils.buildPacket(0x01, ssid, this.keyHex)
		);

		// const pwdData = new TextEncoder().encode(password);
		const pwdPackets = ProtocolUtils.splitPackets(
			ProtocolUtils.buildPacket(0x02, password, this.keyHex)
		);

		await this._sendPackets([...ssidPackets, ...pwdPackets]);
	}

	// 私有方法
	async _scanDevice() {
		console.log("启动查找");
		return new Promise((resolve, reject) => {
			wx.startBluetoothDevicesDiscovery({
				// services: [BLUFI_SERVICE],
				allowDuplicatesKey: false,
				success: () => {
					wx.onBluetoothDeviceFound(res => {
						const devices = res.devices.filter(d =>

							d.advertisServiceUUIDs?.includes(BLUFI_SERVICE)
						);
						console.log("找到的设备是", devices[0]);
						if (devices.length > 0) {
							wx.stopBluetoothDevicesDiscovery();
							resolve(devices[0]);
						}
					});
				},
				fail: err => {
					console.log("启动失败", err);
					reject(false)
				}
			});
		});
	}

	async _connectDevice(device) {
		this.deviceId = device.deviceId;
		this.deviceMac = device.advertisData?.mac || '';
		this.keyHex = CryptoUtils.generateKey(this.deviceMac);

		await wx.createBLEConnection({
			deviceId: this.deviceId
		});
		await wx.setBLEMTU({
			deviceId: this.deviceId,
			mtu: 128
		});
	}

	async _setupServices() {
		const services = await wx.getBLEDeviceServices({
			deviceId: this.deviceId
		});
		if (!services.services.some(s => s.uuid === BLUFI_SERVICE)) {
			throw new Error('未找到 BluFi 服务');
		}

		const chars = await wx.getBLEDeviceCharacteristics({
			deviceId: this.deviceId,
			serviceId: BLUFI_SERVICE
		});

		this._enableNotifications();
	}

	async _enableNotifications() {
		console.log("监听启动");
		wx.notifyBLECharacteristicValueChange({
			deviceId: this.deviceId,
			serviceId: BLUFI_SERVICE,
			characteristicId: NOTIFY_CHAR,
			state: true,
			success: () => {
				console.log("开启通知监听成功");
				wx.onBLECharacteristicValueChange(res => {
					console.log('收到设备响应:', res.value);
				});
			},
			fail: err => {
				console.log("开启通知失败", err);
			}
		});


	}

	async _sendPackets(packets) {
		for (const packet of packets) {
			await wx.writeBLECharacteristicValue({
				deviceId: this.deviceId,
				serviceId: BLUFI_SERVICE,
				characteristicId: WRITE_CHAR,
				value: packet
			});
			await new Promise(resolve => setTimeout(resolve, 20)); // 20ms 间隔
		}
	}

	_checkBluetooth() {
		if (!wx.openBluetoothAdapter) {
			throw new Error('当前版本不支持蓝牙');
		}
		return new Promise((resolve, reject) => {
			uni.openBluetoothAdapter({
				success: (res) => {
					// this.bluetoothState = true
					resolve(true)
				},
				fail: (err) => {
					uni.showToast({
						title: "请开启手机蓝牙",
						icon: "none"
					})
					reject(false)
				}
			})
		})
	}
}